<!--
 * @LastEditTime: 2024-09-03 15:24:38
 * @Description: 高德地图
 * @Date: 2024-08-28 18:48:42
 * @Author: wangshan
 * @LastEditors: wangshan
-->
<script setup>
import { onMounted, onUnmounted, watch } from "vue";
import AMapLoader from "@amap/amap-jsapi-loader";
import { Search } from '@element-plus/icons-vue'
import {info,error} from '@/utils/print.js'
let map = null;
let key = "e465917b0babe411e5a51c7c2020ee39"
let marker = null
let aMap = null;
const addressOptions=ref([])
let props = defineProps({
  position: {
    type: Object,
    default() {
      return {}
    }
  },shopId: {
    type: String
  },
  optionModel: {
    type: String
  }
})

const posi = ref( {})
const searchPosition = ref( props.position.addr)
const nowSelectAddress = ref(null)
error(JSON.stringify(props.position))
// 获取位置
const emits = defineEmits(['update:position'])
const latlngPos=ref({
  lat:'',
  lng:''
})
const addmark = (info) => {
  error('地址1',info.name)
  if (marker) {
    map.remove(marker)
  }
    marker = new aMap.Marker({
      position: new aMap.LngLat(info.lng, info.lat),
      title: info.name || searchPosition.value , // 鼠标滑过点标记时的文字提示
      label: {
        content: info.name || searchPosition.value // 文本标注的内容
      },
      zooms: [12,14] // 点标记显示的层级范围，超过范围不显示。默认值：zooms: [2, 20]
    })
    map.add(marker)
    posi.value=searchPosition.value
    latlngPos.value={
      lat:info.lat,
      lng:info.lng
    }
    map.setCenter([info.lng, info.lat], false, 500) // 中心点 是否直接迁移(动画过度) 过渡时间
}
const getAddress = (lng, lat) => {
      let geocoder = new aMap.Geocoder({
        
      });
       geocoder.getAddress([lng, lat], function (status, result) {
        console.log('====================================');
        console.log(JSON.stringify(result), '地址',lng,lat);
        console.log('====================================');
        if (status === "complete" && result.info === "OK") {
          // result为对应的地理位置详细信息
          // addmark({lng, lat, name: result.regeocode.formattedAddress})
          emits('update:position', {
            addr: result.regeocode.formattedAddress,
            lat:lat,
            lng:lng,
            city: result.regeocode.addressComponent.city || result.regeocode.addressComponent.province
          })
          posi.value = result.regeocode.formattedAddress
        }
      });

  }
const initSearchMap=(str)=>{
  const placeSearch = new aMap.PlaceSearch({
    pageSize: 10, //单页显示结果条数
    pageIndex: 1, //页码
    city: "028", //兴趣点城市
    // citylimit: true, //是否强制限制在设置的城市内搜索
    map: map, //展现结果的地图实例
    // panel: "container", //参数值为你页面定义容器的 id 值<div id="my-panel"></div>，结果列表将在此容器中进行展示。
    autoFitView: true, //是否自动调整地图视野使绘制的 Marker 点都处于视口的可见范围
  });
  placeSearch.search(str,function(status, result){
    console.log(result.info)
    console.log(result)

    if(result.info=='OK'){

      addressOptions.value=result.poiList.pois
      nowSelectAddress.value=0
      changeAddress(0)
      
    }
  }); //使用插件搜索关键字并查看结果
}
const searchAddress = () => {
  initSearchMap(searchPosition.value)
  // getLng(searchPosition.value)
}
const changeAddress = (e) => {
  const pos = addressOptions.value[e]
  emits('update:position', {
    // addr: pos.pname+pos.cityname+pos.adname+ pos.name,
    addr:searchPosition.value,
    lat:pos.location.lat,
    lng:pos.location.lng,
    city: pos.cityname
  })
  // posi.value = pos.pname+pos.cityname+pos.adname+ pos.name
  addmark({lng:pos.location.lng, lat: pos.location.lat, name: pos.name})
}
const getLng = (addr) => {
  var geocoder = new aMap.Geocoder({
  });
  geocoder.getLocation(addr, function (status, result) {
    console.log('====================================');
    console.log('langt===', status, result);
    console.log('====================================');
    if (status === "complete" && result.info === "OK") {
      // result中对应详细地理坐标信息
      console.log(result);
      addressOptions.value=result.geocodes
      nowSelectAddress.value=0
      let pos = result.geocodes[0].location
      addmark({lng:pos.lng, lat: pos.lat, name: result.geocodes[0].formattedAddress})
    }
  });
}

onMounted(() => {
  AMapLoader.load({
    key, // 申请好的Web端开发者Key，首次调用 load 时必填
    version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
    plugins: ['AMap.Scale', 
          "AMap.GeoJSON",
          "AMap.PlaceSearch",
          "AMap.MarkerClusterer",
          "AMap.MouseTool",
          "AMap.Geocoder",], // 需要使用的的插件列表，如比例尺'AMap.Scale'等
  })
    .then((AMap) => {
      aMap = AMap
      map = new AMap.Map("container", {
        // 设置地图容器id
        viewMode: "3D", // 是否为3D地图模式
        zoom: 14, // 初始化地图级别
        center: [104.066301, 30.572961], // 初始化地图中心点位置
      });
        map.on("click", (e) => {
          let lat = e.lnglat.lat;
          let lng = e.lnglat.lng;
          console.log('====================================');
          console.log('e===========', e);
          console.log('====================================');
          getAddress(lng, lat)
        });
        //初始化
        watch(() => props.position, (n) => {
          console.log('posi====================================');
          console.log(n);
          console.log('====================================');
          posi.value = n.addr
          if(n.lng && n.lat){
            addmark({lng:n.lng, lat: n.lat, name: n.addr})
          }
        }, {
          immediate:true
        })
    })
    .catch((e) => {
      console.log(e);
    });
});
 
onUnmounted(() => {
  map?.destroy();
});
</script>
 
<template>
  <div class="map-contaier">
    <!-- <el-input placeholder="点击地图设置区域位置" disabled v-model="posi" style="margin-bottom: 24px"></el-input> -->
    <view>
      <slot>{{latlngPos.lat  }},{{ latlngPos.lng }}</slot>
    </view>
    <el-input
      v-model="searchPosition"
      :disabled="optionModel==='query'"
      @keyup.enter.native="searchAddress"
      style="margin-bottom: 24px;position: absolute;top:60px;left:20px;z-index: 10"
      placeholder="请搜索或点击选择一个位置"
    >
      <template #append>
        <el-button :icon="Search" 
        @Click="searchAddress" />
      </template>
      
    </el-input>
    
    <el-select
    v-if="addressOptions && addressOptions.length>0"
    
    style="margin-bottom: 24px;position: absolute;width: 100%; top:100px;left:20px;z-index: 10"
    v-model="nowSelectAddress"
    @change="changeAddress"
    placeholder="选择" ><el-option
              v-for="(item,i) in addressOptions"
              :key="i"
              :label="item.name"
              :value="i"
            >
            </el-option>
        </el-select>
    <div id="container"></div>
    
  </div>
</template>
 
<style scoped>
.map-contaier {
  width: 100%;
}
#container {
  width: 80vw;
  height: 600px;
}
</style>